﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace YJM.Modbus.Client
{
    public class ModbusInfo
    {
        public int id;
        public string name;
        public byte code;
        public ushort address;
        public string type;
        public ushort length;
        public bool enable;
        public float value;
        public string toString()
        {
            string s = id.ToString() + "," + name + "," + code.ToString() + "," + address.ToString() + "," + type + "," + value.ToString();
            return s;
        }
    }
    public class IndexHelper
    {
        //int:读取的地址，string：读取的数据类型
        public static List<string> index = new List<string>();
        public void getIndex(string filename)
        {
            index.Clear();
            string filepath = Directory.GetCurrentDirectory();
            filepath = filepath + '\\' + filename;
            StreamReader sr = new StreamReader(filepath, Encoding.UTF8);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] msg = line.Split(',');
                if (msg[5] == "true")
                    index.Add(line);
            }
        }
        public ModbusInfo IndexParse(string line)
        {
            ModbusInfo info = new ModbusInfo();
            string[] msg = line.Split(',');
            if (msg.Length == 6)
            {
                info.id = int.Parse(msg[0]);
                info.name = msg[1];
                info.code = Convert.ToByte(msg[2]);
                info.address = Convert.ToUInt16(int.Parse(msg[3]) - 1);
                info.type = msg[4];
                info.enable = bool.Parse(msg[5]);
            }
            if (msg.Length == 7)
            {
                info.id = int.Parse(msg[0]);
                info.name = msg[1];
                info.code = Convert.ToByte(msg[2]);
                info.address = Convert.ToUInt16(int.Parse(msg[3]) - 1);
                info.type = msg[4];
                info.enable = bool.Parse(msg[5]);
                info.value = float.Parse(msg[6]);
            }
            switch (info.type)
            {
                case "int":
                    info.length = 1;
                    break;
                case "float":
                    info.length = 2;
                    break;
                default:
                    break;
            }
            return info;
        }
        //public string ModBusInfo2String(ModbusInfo info)
        //{
        //    string s = "";
        //    s = info.id.ToString() + "," + info.name + "," + info.code.ToString() + "," + info.address.ToString() + "," + info.type;// + "," + info.value.ToString();
        //    return s;
        //}

    }
}
